package com.thenie.chat.controller;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.thenie.chat.pojo.User;
import com.thenie.chat.service.IUserService;
import com.thenie.chat.util.CookieUtil;
import com.thenie.chat.util.UploadUtil;
import com.thenie.chat.util.ValidatorUtil;
import com.thenie.chat.validator.CurrentUser;
import com.thenie.chat.vo.RespBean;
import com.thenie.chat.vo.RespBeanEnum;
import com.thenie.chat.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  用户控制器
 * </p>
 *
 * @author thenie
 * @since 2022-05-17
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;


    /**
     * 注销
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @PostMapping("/logout")
    public RespBean logout(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String userTicket = CookieUtil.getCookieValue(request, "userTicket");

        Boolean ok = userService.deleteUserTicketFormMe(userTicket);

        return RespBean.success("退出账号成功");
    }

    /**
     * 更新用户信息
     * @param user
     * @param userVo
     * @param request
     * @return
     */
    @PostMapping("/update")
    public RespBean update(@CurrentUser User user, UserVo userVo,HttpServletRequest request){
        Long id = user.getId();
        Long userId = userVo.getUserId();
        if (!id.equals(userId)){
            return RespBean.error(RespBeanEnum.UPDATE_USER_ERROR);
        }
        //更新用户信息
        User updateUser = new User(userVo);
        if (userService.updateById(updateUser)){
            RespBean.error(RespBeanEnum.ERROR);
        }
        //更新redis
        String userTicket = CookieUtil.getCookieValue(request, "userTicket");
        User newUser = userService.getOne(new QueryWrapper<User>().eq("id", id));
        newUser.setPassword("");
        newUser.setSalt("");
        redisTemplate.opsForValue().set("userTicket:"+userTicket,newUser,1, TimeUnit.DAYS);

        return RespBean.success();
    }

    /**
     * 上传头像
     * @param user
     * @param userId
     * @param file
     * @param request
     * @return
     * @throws IOException
     */
    @PostMapping("/uploadPhoto")
    public RespBean uploadPhoto(@CurrentUser User user,Long userId,@RequestParam("photo") MultipartFile file,
                                HttpServletRequest request) throws IOException {
        //生成唯一文件名
        String photoName = UploadUtil.randomImgName(file);
        //上传图片，获取返回结果
        JSONObject resp = JSONUtil.parseObj(UploadUtil.uploadImg(file.getBytes(), photoName).body());
        Boolean status = (Boolean) resp.get("status");
        if (!status) {//上传失败
            return RespBean.error(RespBeanEnum.UPDATE_USER_ERROR);
        }
        //获取返回信息
        JSONObject data = JSONUtil.parseObj(resp.get("data"));
        //获取访问图片的 路径+文件名
        String absPathName = UploadUtil.getImgLookPrefix()+data.getStr("pathname");
        //更新数据库
        User updateUser = new User();
        updateUser.setId(userId);
        updateUser.setPhoto(absPathName);

        if (!userService.updateById(updateUser)){//失败
            return RespBean.error(RespBeanEnum.ERROR);
        }
        //更新redis
        String userTicket = CookieUtil.getCookieValue(request, "userTicket");
        user.setPhoto(absPathName);
        redisTemplate.opsForValue().set("userTicket:"+userTicket, user,1,TimeUnit.DAYS);

        return RespBean.success(absPathName);
    }

    /**
     * 查找用户
     * @param info 用户名或邮箱
     * @return
     */
    @GetMapping("/selectUser/{info}")
    public RespBean selectUser(@PathVariable String info){
        User user = null;
        if (!StringUtils.isEmpty(info)){
            if (ValidatorUtil.isEmail(info)){
                user = userService.getUserByEmail(info);
            }else{
                user = userService.getUserByUsername(info);
            }
            if (user!=null){
                return RespBean.success(user);
            }
        }

        return RespBean.error(RespBeanEnum.SESSION_ERROR);
    }

    /**
     * 根据id查找用户
     * @param id
     * @return
     */
    @GetMapping("/selectUser")
    public RespBean selectUserById(@RequestParam("id") Long id){
        User user = userService.getById(id);
        if (user == null){
            return RespBean.error(RespBeanEnum.SESSION_ERROR);
        }
        user.setSalt("");
        user.setPassword("");
        return RespBean.success(user);
    }

}
